 
package com.zdkj.subway.rca.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.util.DateUtils;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.rca.entity.ViewCkDataauditReportCheck;
import com.zdkj.subway.rca.mapper.ViewCkDataauditReportCheckMapper;
import com.zdkj.subway.rca.service.ViewCkDataauditReportCheckService;
import com.zdkj.subway.rca.util.LocalDateConverter;
import com.zdkj.subway.rca.util.LocalDateTimeConverter;
import com.zdkj.subway.rca.util.MyDateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 西安地铁收入报表与对账数据复核
 *
 * @author stw
 * @date 2020-11-15 12:52:06
 */
@Service
public class ViewCkDataauditReportCheckServiceImpl extends ServiceImpl<ViewCkDataauditReportCheckMapper, ViewCkDataauditReportCheck> implements ViewCkDataauditReportCheckService {
    private static final Logger log = LoggerFactory.getLogger(ViewCkDataauditReportCheckServiceImpl.class);

    /**
     * 产生数据
     * @return
     */
    @Override
    public Boolean generate(String startDate,String endDate) throws Exception {

        List<String> listDate = MyDateUtil.getDatesBetweenTwoDate(startDate,endDate);

        //根据日期范围获取数据list
		/*
        List<Map<String,Object>> dataListA = this.baseMapper.getDataListA(startDate,endDate);
        List<Map<String,Object>> dataListB = this.baseMapper.getDataListB(startDate,endDate);
        List<Map<String,Object>> dataListC = this.baseMapper.getDataListC(startDate,endDate);
        List<Map<String,Object>> dataListD = this.baseMapper.getDataListD(startDate,endDate);
		*/
        //List<Map<String,Object>> dataListE = this.baseMapper.getDataListE(startDate,endDate);
        //List<Map<String,Object>> dataListF = this.baseMapper.getDataListF(startDate,endDate);
        List<Map<String,Object>> dataListG = this.baseMapper.getDataListG(startDate,endDate);
        List<Map<String,Object>> dataListH = this.baseMapper.getDataListH(startDate,endDate);

        List<Map<String,Object>> dataListJ = this.baseMapper.getDataListJ(startDate,endDate);

        List<Map<String,Object>> dataListL = this.baseMapper.getDataListL(startDate,endDate);
        /*
		List<Map<String,Object>> dataListM = this.baseMapper.getDataListM(startDate,endDate);
        List<Map<String,Object>> dataListN = this.baseMapper.getDataListN(startDate,endDate);
		*/
        /*List<Map<String,Object>> dataListO = this.baseMapper.getDataListO(startDate,endDate);
        List<Map<String,Object>> dataListP = this.baseMapper.getDataListP(startDate,endDate);*/
        //List<Map<String,Object>> dataListQ = this.baseMapper.getDataListQ(startDate,endDate);
        //List<Map<String,Object>> dataListR = this.baseMapper.getDataListR(startDate,endDate);

        List<ViewCkDataauditReportCheck> updaeList = new ArrayList<>();
        List<ViewCkDataauditReportCheck> insertList = new ArrayList<>();

        PigxUser user = SecurityUtils.getUser();

        //循环时间段内每一天
        for(String tradeDate : listDate) {
            ViewCkDataauditReportCheck insertObj = new ViewCkDataauditReportCheck();
            insertObj.setStatisticsDate(LocalDate.parse(tradeDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")));

            //数据库老的
            ViewCkDataauditReportCheck dbViewCkDataauditReportCheck = this.getOne(Wrappers.query(insertObj));
            if (dbViewCkDataauditReportCheck != null){
                insertObj.setId(dbViewCkDataauditReportCheck.getId());
            }

            /*不需要BOM小额
			insertObj.setBomAlipay(getData(tradeDate,"BOM_ALIPAY",dataListA));
            insertObj.setBomWechat(getData(tradeDate,"BOM_WECHAT",dataListB));
            insertObj.setBomAlipayCompare(getData(tradeDate,"BOM_ALIPAY_COMPARE",dataListC));
            insertObj.setBomWechatCompare(getData(tradeDate,"BOM_WECHAT_COMPARE",dataListD));
            insertObj.setDiffBomAlipay(insertObj.getBomAlipay().subtract(insertObj.getBomAlipayCompare()));
            insertObj.setDiffBomAlipay(insertObj.getBomWechat().subtract(insertObj.getBomWechatCompare()));
			*/
			insertObj.setBomAlipay(new BigDecimal(0.00));
            insertObj.setBomWechat(new BigDecimal(0.00));
            insertObj.setBomAlipayCompare(new BigDecimal(0.00));
            insertObj.setBomWechatCompare(new BigDecimal(0.00));
            insertObj.setDiffBomAlipay(new BigDecimal(0.00));
            insertObj.setDiffBomAlipay(new BigDecimal(0.00));
            //二维码  不需要二维码   2021-10-26
			/*
            insertObj.setQrAlipay(getData(tradeDate,"QR_ALIPAY",dataListE));
            insertObj.setQrWechat(getData(tradeDate,"QR_WECHAT",dataListE));
            insertObj.setQrBank(getData(tradeDate,"QR_BANK",dataListE));

            insertObj.setQrAlipayCompare(getData(tradeDate,"QR_ALIPAY_COMPARE",dataListF));
            insertObj.setQrWechatCompare(getData(tradeDate,"QR_WECHAT_COMPARE",dataListF));
            insertObj.setQrBankCompare(getData(tradeDate,"QR_BANK_COMPARE",dataListF));

            insertObj.setDiffQrAlipay(insertObj.getQrAlipay().subtract(insertObj.getQrAlipayCompare()));
            insertObj.setDiffQrWechat(insertObj.getQrWechat().subtract(insertObj.getQrWechatCompare()));
            insertObj.setDiffQrBank(insertObj.getQrBank().subtract(insertObj.getQrBankCompare()));
			*/
			insertObj.setQrAlipay(new BigDecimal(0.00));
            insertObj.setQrWechat(new BigDecimal(0.00));
            insertObj.setQrBank(new BigDecimal(0.00));

            insertObj.setQrAlipayCompare(new BigDecimal(0.00));
            insertObj.setQrWechatCompare(new BigDecimal(0.00));
            insertObj.setQrBankCompare(new BigDecimal(0.00));

            insertObj.setDiffQrAlipay(new BigDecimal(0.00));
            insertObj.setDiffQrWechat(new BigDecimal(0.00));
            insertObj.setDiffQrBank(new BigDecimal(0.00));
            
			//长安通
            insertObj.setCatcardSystem(getData(tradeDate,"CATCARD_SYSTEM",dataListG));
            insertObj.setCatcardSysttemCompare(getData(tradeDate,"CATCARD_SYSTTEM_COMPARE",dataListH));
            insertObj.setDiffCatcardSysttem(insertObj.getCatcardSystem().subtract(insertObj.getCatcardSysttemCompare()));

            insertObj.setRecharge(getData(tradeDate,"RECHARGE",dataListG));
            insertObj.setRechargeCompare(getData(tradeDate,"RECHARGE_COMPARE",dataListJ));
            insertObj.setDiffRecharge(insertObj.getRecharge().subtract(insertObj.getRechargeCompare()));

            insertObj.setJtcardSystem(getData(tradeDate,"JTCARD_SYSTEM",dataListG));
            insertObj.setJtcardSysttemCompare(getData(tradeDate,"JTCARD_SYSTTEM_COMPARE",dataListL));
            insertObj.setDiffJtcardSysttem(insertObj.getJtcardSystem().subtract(insertObj.getJtcardSysttemCompare()));
            /*不需要ITVM
            insertObj.setItvmAlipay(getData(tradeDate,"ITVM_ALIPAY",dataListM));
            insertObj.setItvmWechat(getData(tradeDate,"ITVM_WECHAT",dataListM));
            insertObj.setItvmBank(getData(tradeDate,"ITVM_BANK",dataListM));

            insertObj.setItvmAlipayCompare(getData(tradeDate,"ITVM_ALIPAY_COMPARE",dataListN));
            insertObj.setItvmWechatCompare(getData(tradeDate,"ITVM_WECHAT_COMPARE",dataListO));
            insertObj.setItvmBankCompare(getData(tradeDate,"ITVM_BANK_COMPARE",dataListP));

            insertObj.setDiffItvmAlipay(insertObj.getItvmAlipay().subtract(insertObj.getItvmAlipayCompare()));
            insertObj.setDiffItvmWechat(insertObj.getItvmWechat().subtract(insertObj.getItvmWechatCompare()));
            insertObj.setDiffItvmBank(insertObj.getItvmBank().subtract(insertObj.getItvmBankCompare()));
			*/
			
            insertObj.setItvmAlipay(new BigDecimal(0.00));
            insertObj.setItvmWechat(new BigDecimal(0.00));
            insertObj.setItvmBank(new BigDecimal(0.00));

            insertObj.setItvmAlipayCompare(new BigDecimal(0.00));
            insertObj.setItvmWechatCompare(new BigDecimal(0.00));
            insertObj.setItvmBankCompare(new BigDecimal(0.00));

            insertObj.setDiffItvmAlipay(new BigDecimal(0.00));
            insertObj.setDiffItvmWechat(new BigDecimal(0.00));
            insertObj.setDiffItvmBank(new BigDecimal(0.00));

            /*不需要人脸  2021-10-26
            insertObj.setFaceBank(getData(tradeDate,"FACE_BANK",dataListQ));
            insertObj.setFaceBankCompare(getData(tradeDate,"FACE_BANK_COMPARE",dataListR));
            insertObj.setDiffFaceBank(insertObj.getFaceBank().subtract(insertObj.getFaceBankCompare()));
			*/

			insertObj.setFaceBank(new BigDecimal(0.00));
            insertObj.setFaceBankCompare(new BigDecimal(0.00));
            insertObj.setDiffFaceBank(new BigDecimal(0.00));

            insertObj.setDeptId(user.getDeptId());
            insertObj.setCreatorId(user.getId());
            insertObj.setCreatorName(user.getNikeName());
            if(insertObj.getId() != null){
                updaeList.add(insertObj);
            } else {
                insertList.add(insertObj);
            }

        }
        boolean flag = false;
        boolean flag2 = false;
        if(!updaeList.isEmpty()){
            flag = this.updateBatchById(updaeList);
			if(flag){
			   //MP的字段默认更新策略
				for (ViewCkDataauditReportCheck reportCheck : updaeList) {
					this.update(null,Wrappers.<ViewCkDataauditReportCheck>lambdaUpdate()
							.set(ViewCkDataauditReportCheck::getConformStatus,"0")
							.set(ViewCkDataauditReportCheck::getConformTime,null).eq(ViewCkDataauditReportCheck::getId,reportCheck.getId()));
				}
			}
			 
        }
        if(!insertList.isEmpty()){
            flag2 = this.saveBatch(insertList);
        }
        return  flag || flag2;
    }


    private BigDecimal getData(String tradeDate,String key, List<Map<String,Object>> dataList){
        if(dataList == null || dataList.isEmpty()) {
            return new BigDecimal(0);
        }
        for(Map<String,Object> map : dataList) {
            if(tradeDate.equals(DateUtils.format((Date)map.get("TRADE_DATE"),"yyyy-MM-dd"))) {               
				//return (BigDecimal) map.get(key);
				BigDecimal initValue =  (BigDecimal) map.get(key);				
				return initValue.setScale(2, BigDecimal.ROUND_HALF_UP);
            }
        }
        return new BigDecimal(0);
    }

    /**
     * 导出
     * @param
     * @return
     * @throws IOException
     */
    @Override
    public void exportExcel(String startDate, String endDate, HttpServletResponse response) {
        ViewCkDataauditReportCheck viewCkDataauditReportCheck = new ViewCkDataauditReportCheck();
        List<ViewCkDataauditReportCheck> records  = this.list(Wrappers.query(viewCkDataauditReportCheck).lambda().ge(StringUtils.isNotEmpty(startDate), ViewCkDataauditReportCheck::getStatisticsDate, startDate).le( StringUtils.isNotEmpty(endDate),ViewCkDataauditReportCheck::getStatisticsDate, endDate));
        InputStream excelTemplateIs = null;
        try {response.reset(); // 非常重要
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            final String fileName = URLEncoder.encode("西安地铁收入报表与对账数据复核", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");

            // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
            // {} 代表普通变量 {.} 代表是list的变量

            excelTemplateIs = this.getClass().getResourceAsStream("/static/excel/template/export/ViewCkDataauditReportCheckExcelTemplate.xlsx");

            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).registerConverter(new LocalDateTimeConverter()).registerConverter(new LocalDateConverter()).withTemplate(excelTemplateIs).build();
            WriteSheet writeSheet = EasyExcel.writerSheet("西安地铁收入报表与对账数据复核").build();
            // 这里注意 入参用了forceNewRow 代表在写入list的时候不管list下面有没有空行 都会创建一行，然后下面的数据往后移动。默认 是false，会直接使用下一行，如果没有则创建。
            // forceNewRow 如果设置了true,有个缺点 就是他会把所有的数据都放到内存了，所以慎用
            // 简单的说 如果你的模板有list,且list不是最后一行，下面还有数据需要填充 就必须设置 forceNewRow=true 但是这个就会把所有数据放到内存 会很耗内存
            // 如果数据量大 list不是最后一行 参照另一个
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.FALSE).build();
            excelWriter.fill(records, fillConfig, writeSheet);

            excelWriter.finish();

        } catch (Exception e) {
            e.printStackTrace();
            log.error("导出西安地铁收入报表与对账数据复核错误");
        } finally {
            if(excelTemplateIs != null){
                try {
                    excelTemplateIs.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }

            }
        }
    }
}
